package choiceComplex

import (
	"encoding/json"
	"log"

	"smartconn.cc/tosone/parsing/config"
	"smartconn.cc/tosone/parsing/handler/choice"
	"smartconn.cc/tosone/parsing/lib/audioMgr"
	"smartconn.cc/tosone/parsing/lib/util"
	"smartconn.cc/tosone/parsing/model"
)

var keywords []string
var channel chan string

// Index 复杂选择模式的入口
func Index(res model.RegexResult, options model.ModelsOptions) model.ModeResponse {
	channel = make(chan string, 1)
	saidNothing := config.Audio["saidNothing"]
	saidWrong := config.Audio["saidWrong"]
	defaultAudio := ""
	beforeAudio := ""

	var structContent model.ChoiceComplexModel
	json.Unmarshal([]byte(res.Con), &structContent)
	defaultAudioOnce := true
	for _, v := range structContent {
		// 默认音频
		switch v.Sound.(type) {
		case string:
			if defaultAudioOnce {
				defaultAudioOnce = false
				defaultAudio = v.Sound.(string)
			} else if v.Default {
				defaultAudio = v.Sound.(string)
			}
		case []interface{}:
			list := v.Sound.([]interface{})
			ran := util.Random(len(list))
			if defaultAudioOnce {
				defaultAudioOnce = false
				defaultAudio = list[ran].(string)
			} else if v.Default {
				defaultAudio = list[ran].(string)
			}
		}
		// 收集关键词
		keywords = append(keywords, v.Keyword...)
		// 查找设置的 saidNothing
		log.Println(v.SaidNothing)
		if v.SaidNothing != nil {
			switch v.SaidNothing.(type) {
			case string:
				saidNothing = v.SaidNothing.(string)
			case []interface{}:
				list := v.SaidNothing.([]interface{})
				ran := util.Random(len(list))
				saidNothing = list[ran].(string)
			}
		}
		// 查找设置的 saidWrong
		if v.SaidWrong != nil {
			switch v.SaidWrong.(type) {
			case string:
				saidWrong = v.SaidWrong.(string)
			case []interface{}:
				list := v.SaidWrong.([]interface{})
				ran := util.Random(len(list))
				saidNothing = list[ran].(string)
			}
		}
		// 查找设置的 before
		if v.Before != nil {
			switch v.Before.(type) {
			case string:
				beforeAudio = v.Before.(string)
			case []interface{}:
				list := v.Before.([]interface{})
				ran := util.Random(len(list))
				beforeAudio = list[ran].(string)
			}
		}
	}
	if beforeAudio != "" {
		audioMgr.Play(beforeAudio, 0)
	}
	go choice.RecordChoice(5, false, 1, "", keywords, channel, saidNothing, saidWrong)
	result := <-channel
	if result == "" {
		audioMgr.Play(defaultAudio, 0)
	} else {

	}
	return model.ModeResponse{Sound: []string{}, Backline: 1}
}

// Stop 停止复杂的选择模式
func Stop() {

}
